package airthmetic.exercise.tree;

import java.util.LinkedList;
import java.util.Queue;

public class _111_二叉树的最小深度 {
    // 广度优先
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList();
        int level = 1;
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0; i<size; i++){
                TreeNode n = queue.poll();
                if(n.left == null && n.right == null){
                    return level;
                }
                if(n.left != null){
                    queue.offer(n.left);
                }
                if(n.right != null){
                    queue.offer(n.right);
                }
            }
            level++;
        }

        return level;
    }

    // 深度优先
    public static int minDepth3(TreeNode root) {
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
        if(root.left == null){
            return  minDepth3(root.right)+1;
        }
        if(root.right == null){
            return  minDepth3(root.left)+1;
        }
        return Math.min(minDepth3(root.left),minDepth3(root.right))+1;
    }


    public static void main(String[] args) {

        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode2 = new TreeNode(2,treeNode4, treeNode5);
        TreeNode treeNode = new TreeNode(1,treeNode2,treeNode3);

        int i3 = minDepth3(treeNode);
        System.out.println(i3);

    }











}
